import { useEffect, useState } from 'react'
import {
	useAppDispatch,
	useAppSelector,
	useDebounce,
	useSelectProducts,
} from '../../hooks'
import {
	selectCatalogMaxPage,
	selectCatalogPage,
} from '../../store/reducers/selectors'
import { LoadMore } from '../catalog/loadMore'
import { paginationSlice } from '../../store/reducers/slices/paginationSlice'

const Pagination = () => {
	const catalogMaxPage = useAppSelector(selectCatalogMaxPage)
	const selectedCatalogPage = useAppSelector(selectCatalogPage)

	const dispatch = useAppDispatch()

	const { data } = useSelectProducts()

	const [selectedPage, setSelectedPage] = useState(selectedCatalogPage)

	const isEndOfList = (data?.products.length || 0) >= (data?.total || 0)
	const selectedPageDebounce =
		useDebounce({ value: selectedPage, delay: 2000 }) || ''

	// изменение стейта через пользователя
	useEffect(() => {
		dispatch(paginationSlice.actions.setPage(selectedPageDebounce))
	}, [dispatch, selectedPageDebounce])

	// изменение стейта через стор
	useEffect(() => {
		setSelectedPage(selectedCatalogPage)
	}, [selectedCatalogPage])

	return (
		<>
			{!!data && (
				<LoadMore
					action={() => {
						setSelectedPage(
							selectedCatalogPage < catalogMaxPage
								? selectedCatalogPage + 1
								: selectedCatalogPage
						)
					}}
					isLoading={!isEndOfList}
					isEndOfList={isEndOfList}
				/>
			)}
		</>
	)
}

export default Pagination
